package com.yang.thread.syn;

/**
 * @author yds
 * @program thread-study
 * @description 加锁线程安全
 * @create 2020-09-22 17:11
 **/
public class ThreadSafe implements Runnable {
    private int count = 6;
    private static Object object = new Object();

    @Override
    public void run() {
        while (count > 0) {
            try {
                Thread.sleep(100);
                sale();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    }

    /**
     * 售票方法，解耦合
     */
    public  void sale() {
        synchronized(object){
            if (count > 0) {
                System.out.println(Thread.currentThread().getName() + ",拿到了出售的第" + (6 - count + 1) + "张票");
                count--;
            }
        }

    }

    public static void main(String[] args) {
        ThreadSafe t1 = new ThreadSafe();
        new Thread(t1, "小杨").start();
        new Thread(t1, "小张").start();
    }
}